package cn.my.framework.config;

import cn.my.framework.util.ConstantData;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by zhangl_lc on 2017/7/5.
 */
@ControllerAdvice
public class MyControllerAdvice {

    Logger logger = LoggerFactory.getLogger(MyControllerAdvice.class);

    @ExceptionHandler(value = Exception.class)
    public ModelAndView handleException(HttpServletRequest req,Exception ex){
        logger.debug(">>>>> caught Exception : {}",ex);
        ModelAndView mav = new ModelAndView("error");
        String errorCode = "1000";
        mav.addObject("code","1000");
        mav.addObject("message", ConstantData.codeDescMap.get(errorCode));
        String detail = ex.toString();
        if(ConstantData.errorDetailShow){
            detail += (":\n\n"+ wrapStackTrace(ex.getStackTrace()));
        }
        mav.addObject("detail",detail);
        return mav;
    }

    @ModelAttribute
    public void addAttributes(Model model) {
        //绑定值到Model中，在controller执行前，绑定到ModelMap、ModelAttribute等对象中
        //model.addAttribute("author", "leo");
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        //应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器
    }

    public static String wrapStackTrace (StackTraceElement[] stes){
        if(stes != null && stes.length > 0){
            return StringUtils.join(stes,"\n");
        }
        return "无错误详情";
    }

}
